package icu.lookyousmileface.volatilecode;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author starrysky
 * @title: VolatileNotAtomic
 * @projectName Juc_Pro
 * @description: Volatile不保证原子性
 * @date 2021/1/3011:32 上午
 */
public class VolatileNotAtomic {

    private volatile static int num = 0;

    public  static void add(){
        num++;
    }

    public static void main(String[] args) {


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,
                Runtime.getRuntime().availableProcessors(),
                5,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        try {
            for (int i = 1; i <= 20; i++) {
                threadPoolExecutor.execute(() -> {
                    for (int j = 1; j <= 1000; j++) {
                        add();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }
        Thread.currentThread().getThreadGroup().list();

        System.out.println("sum:" + num);

    }
}
